import 'dart:math';

import 'package:dali_ng_pera/mob/dnp_mob.dart';
import 'package:dali_ng_pera/page/certification/controller/dnp_emergency_controller.dart';
import 'package:dali_ng_pera/plugin/dnp_plugin/lib/dnp_plugin.dart';
import 'package:dali_ng_pera/tool/dnp_time_tool.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../widget/dnp_app_bar.dart';
import 'dialog/dnp_single_choice_dialog.dart';
import 'model/dnp_emergency_model.dart';

class DnpEmergencyPage extends StatefulWidget {
  final String already;
  final String title;
  const DnpEmergencyPage({super.key, required this.already, required this.title});

  @override
  State<DnpEmergencyPage> createState() => _DnpEmergencyPageState();
}

class _DnpEmergencyPageState extends State<DnpEmergencyPage> {
  final controller = Get.put(DnpEmergencyController());
  int startTime = 0;

  @override
  void initState() {
    super.initState();
    startTime = DnpTimeTool.timestamp;
    controller.onRequestData(widget.already);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF53A9FF),
              Color(0xFFDFF1FF),
            ],
          ),
        ),
        child: Column(
          children: [
            DnpAppBar(title: widget.title),
            Expanded(
                child: SingleChildScrollView(
              child: Obx(() => Column(
                    children: [
                      ...controller.emergencyModels
                          .asMap()
                          .entries
                          .map((entry) {
                        final item = entry.value;
                        return _buildItem(item);
                      }).toList(),
                      SizedBox(height: 20),
                    ],
                  )),
            )),
            _buildBottomButton(),
            SizedBox(height: 34),
          ],
        ),
      ),
    );
  }

  Widget _buildItem(DnpEmergencyModel model) {
    return Container(
      alignment: Alignment.centerLeft,
      width: double.infinity,
      margin: EdgeInsets.only(left: 14, right: 14, top: 14),
      padding: EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(20)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            model.discernible ?? "",
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xFF252630)),
          ),
          SizedBox(height: 15),
          Text(
            model.heathen ?? "",
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w400,
                color: Color(0xFF252630)),
          ),
          SizedBox(height: 13),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              _showSingleChoiceDialog(model);
            },
            child: Container(
              width: double.infinity,
              padding:
                  EdgeInsets.only(left: 14, right: 14, top: 14, bottom: 15),
              decoration: BoxDecoration(
                color: Color(0xFFE9F5FF),
                borderRadius: BorderRadius.all(Radius.circular(16)),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      (model.christian == null || model.christian == "")
                          ? model.entered ?? ""
                          : controller.getBeersheba(model.christian, model.usually),
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight:
                            (model.christian == null || model.christian == "")
                                ? FontWeight.w400
                                : FontWeight.w500,
                        color: Color(
                            (model.christian == null || model.christian == "")
                                ? 0xFFABABAB
                                : 0xFF252630),
                      ),
                    ),
                  ),
                  Image.asset(
                    "assets/images/ic_emergency_arrow.png",
                    width: 18,
                    height: 18,
                  )
                ],
              ),
            ),
          ),
          SizedBox(height: 12),
          Text(
            model.broken ?? "",
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w400,
                color: Color(0xFF252630)),
          ),
          SizedBox(height: 13),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () async {
              DnpMob.night();
              dynamic result = await DnpPlugin().chooseContact;
              model.beersheba = result["fullName"] ?? "";
              model.most = result["phoneNumber"] ?? "";
              controller.emergencyModels.refresh();
            },
            child: Container(
              width: double.infinity,
              padding:
                  EdgeInsets.only(left: 14, right: 14, top: 14, bottom: 15),
              decoration: BoxDecoration(
                color: Color(0xFFE9F5FF),
                borderRadius: BorderRadius.all(Radius.circular(16)),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      ((model.most == null || model.most == "") && (model.beersheba == null || model.beersheba == ""))
                          ? model.arm ?? ""
                          : "${model.beersheba} ${model.most!}",
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: (model.most == null || model.most == "")
                            ? FontWeight.w400
                            : FontWeight.w500,
                        color: Color(((model.most == null || model.most == "") && (model.beersheba == null || model.beersheba == ""))
                            ? 0xFFABABAB
                            : 0xFF252630),
                      ),
                    ),
                  ),
                  Image.asset(
                    "assets/images/ic_emergency_arrow.png",
                    width: 18,
                    height: 18,
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomButton() {
    return GestureDetector(
      onTap: () {
        controller.onSubmit(widget.already,(){
          DnpMob.inexplicable("7", startTime, DnpTimeTool.timestamp);
        });
      },
      child: Container(
        width: double.infinity,
        height: 48,
        alignment: Alignment.center,
        margin: EdgeInsets.only(left: 24, right: 24, top: 10),
        decoration: BoxDecoration(
          color: Color(0xFF1D4AC8),
          borderRadius: BorderRadius.all(Radius.circular(16)),
        ),
        child: Text(
          "Next",
          style: TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  void _showSingleChoiceDialog(DnpEmergencyModel item) {
    // 从 usually 列表中提取选项
    final options = item.usually?.map((e) => e.beersheba ?? '').toList() ?? [];
    if (options.isEmpty) return;

    // 获取当前已选中的值
    final currentValue = item.beersheba;

    showDialog(
      context: context,
      builder: (context) {
        return DnpSingleChoiceDialog(
          title: item.discernible ?? "",
          options: options,
          selectedOption: currentValue,
          onConfirm: (value) {
            item.christian = (item.usually ?? [])
                    .firstWhere((e) => e.beersheba == value)
                    .heard ??
                "";
            controller.emergencyModels.refresh();
          },
        );
      },
    );
  }

  /// 生成随机十一位数
  String generateRandomElevenDigitNumber() {

    final random = Random();
    // 第一位数不能为0，所以范围是1-9
    final firstDigit = random.nextInt(9) + 1;
    // 后十位数可以是0-9
    final remainingDigits = List.generate(10, (_) => random.nextInt(10)).join();

    return '$firstDigit$remainingDigits';
  }
}
